<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<title>Start CI builds</title>
	<style type="text/css">
		body {
			margin: 40px auto;
			max-width: 30em;
			line-height: 1.6;
			color: #444;
			padding: 0 10px;
		}

		div {
			border: 1px solid gray;
			white-space: pre-wrap;
		}

		label {
			width: 10em;
			display: inline-block;
		}

		input {
			width: 15em;
			display: inline-block;
		}

		textarea {
			width: 90%;
		}
	</style>
	<script>
		function $(id) { return document.getElementById(id); }
		function formval(formid) { return $(formid).value; }
		function updateEnvBox(box) {
			envdata = JSON.parse(formval(box));
			envdata.CMakeArgs = formval('cmakeargs');
			envdata.DODEPLOY = $('dodeploy').checked ? "true" : "false";
			$(box).value = JSON.stringify(envdata, null, 2);
			return envdata;
		}
		function savesettings() {
			if (window.location.protocol !== 'file:') {
				alert('Credentials are only saved on local (file://C:/foo.html) files');
				return;
			}
			for (inp of document.getElementsByTagName('input')) {
				window.localStorage.setItem(inp.id, inp.value);
			}
		}
		function xhr(url, headers, data, cb) {
			var req = new XMLHttpRequest();
			req.open('POST', url);
			headers['Content-Type'] = 'application/json';
			for (let key in headers) req.setRequestHeader(key, headers[key]);
			req.onload = () => {
				$('result').textContent = req.response;
				console.log(req);
				try {
					cb(JSON.parse(req.response));
				} catch (err) { alert(err); }
			}
			let datastr = JSON.stringify(data, null, 2);
			$('request').textContent = datastr;
			req.send(datastr);
		}
		function buildtravis() {
			let data = { 'request': { 'config': { 'env': updateEnvBox('travisenv') } } };
			if (branch = formval('branch')) { data.request.branch = branch; }

			let reponame = formval('accountName') + '%2F' + formval('projectSlug');
			let url = `https://api.travis-ci.org/repo/${reponame}/requests`;
			let headers = { 'Travis-API-Version': 3, 'Authorization': 'token ' + formval('trtoken') };
			xhr(url, headers, data, (resp) => { });
		};
		// Useful presets for AppVeyor
		// Keys: `env` contains environment settings, `CMakeArgs` (optional) arguments to CMake
		let appveyorcompilers = {
			'Default': {},
			'VS2015 x64 new image': { 'VCVER': '14.0', 'ARCH': 'amd64', 'QTCOMPILER': 'msvc2017_64', 'APPVEYOR_BUILD_WORKER_IMAGE': 'Visual Studio 2017' },
			'VS2015 x64': { 'VCVER': '14.0', 'ARCH': 'amd64', 'QTCOMPILER': 'msvc2015_64' },
			'VS2008 x86': { 'VCVER': '9.0', 'ARCH': 'x86', 'QTCOMPILER': 'not supported' }
		}
		function buildappveyor() {
			try {
				let data = {
					'accountName': formval('accountName'),
					'projectSlug': formval('projectSlug'),
					'environmentVariables': updateEnvBox('appveyorenv'),
				};
				if (branch = formval('branch')) data.branch = branch;

				let headers = { 'Authorization': 'Bearer ' + formval('avtoken') };
				let cb = (resp) => {
					let link = document.createElement('a');
					link.href = `https://ci.appveyor.com/project/${formval('accountName')}/${formval('projectSlug')}/build/${resp.version}`;
					link.textContent = 'Build log';
					$('result').appendChild(link);
				}
				let url = `https://ci.appveyor.com/api/account/${formval('accountName')}/builds`;
				xhr(url, headers, data, cb);
			}
			catch (err) {
				alert('Invalid JSON in AppVeyor environment settings' + err);
			}
		}
		function updategithublink() {
			let org = formval('accountName');
			let repo = formval('projectSlug');
			let link = `https://github.com/${org}/${repo}`;
			let a = $('githublink');
			a.textContent = link;
			a.href = link;
		}
		document.addEventListener("DOMContentLoaded", () => {
			for (inp of document.getElementsByTagName('input')) {
				if (inp.type == 'button') continue;
				let savedval = window.localStorage.getItem(inp.id);
				if (savedval !== null) inp.value = savedval;
			}

			for (key in appveyorcompilers) {
				var option = document.createElement('option');
				option.textContent = option.value = key;
				$('avcompiler').appendChild(option);
			}
			$('avcompiler').onchange = (ev) => {
				$('appveyorenv').value = JSON.stringify(appveyorcompilers[formval('avcompiler')], null, 2);
				updateEnvBox('appveyorenv');
			};
			let updateEnvBoxes = (e) => {
				updateEnvBox('travisenv');
				updateEnvBox('appveyorenv');
			};
			$('cmakeargs').addEventListener('change', updateEnvBoxes);
			$('dodeploy').addEventListener('change', updateEnvBoxes);
			$('repoAccountName').addEventListener('change', updategithublink);
			$('projectSlug').addEventListener('change', updategithublink);
			updategithublink();
		});
	</script>
</head>

<body>
	<h1>CI build console</h1>
	<h2>What's this for?</h2>
	<span>LSL supports a large range of systems, from tiny Raspberry Pis and Android/iOS Phones to large PCs with Windows,
		Linux
		and OS X. Before proposing changes, it's therefore a good idea to test if your code compiles and runs on these
		platforms.
		You can register with your GitHub Account at
		<a href="https://appveyor.com" target="_blank">AppVeyor</a>
		and
		<a href="https://travis-ci.com" target="_blank">Travis CI</a> and compile your code on most supported systems. To do
		this, request your API tokens (see links below) and
		fill out the forms below to start a CI build and see if everything works.
	</span>
	<form action="#">
		<datalist id="accountNameList">
			<option value="labstreaminglayer" />
		</datalist>
		<datalist id="repoAccountNameList">
			<option value="labstreaminglayer" />
			<option value="sccn" />
		</datalist>
		<datalist id="projectSlugList">
			<option value="liblsl" />
			<option value="App-LabRecorder" />
		</datalist>
		<datalist id="cmakeargsList">
			<option value="-DLSL_LSLBOOST_PATH=external" />
			<option value="-DLSL_LSLBOOST_PATH=lslboost -DCMAKE_INTERPROCEDURAL_OPTIMIZATION:BOOL=1 -DCMAKE_POLICY_DEFAULT_CMP0069=NEW" />
		</datalist>
		<fieldset>
			<legend>Account / Repo settings</legend>
			<label for="accountName">CI Account:</label>
			<input id="accountName" type="text" list="accountNameList" />
			<br>
			<label for="projectSlug">Repo Name:</label>
			<input id="projectSlug" type="text" list="projectSlugList" />
			<br>
			Github link: <a id="githublink" href="#">(calculated)</a>
			<br>
			<label for="avtoken">
				<a href="https://ci.appveyor.com/api-keys" target="_blank">AppVeyor-Token:</a>
			</label>
			<input id="avtoken" type="text" value="" />
			<br>
			<label for="trtoken">
				<a href="https://docs.travis-ci.com/user/triggering-builds/" target="_blank">Travis-Token:</a>
			</label>
			<input id="trtoken" type="text" value="" />
			<br>
			<input type="button" value="Save settings locally" onclick="savesettings()">
		</fieldset>
		<fieldset>
			<legend>Build settings</legend>
			<label for="branch">Branch (optional):</label>
			<input id="branch" type="text" />
			<br>
			<label for="cmakeargs">CMake args:</label>
			<input id="cmakeargs" type="text" list="cmakeargsList" />
			<br>
			<label for="dodeploy">Deploy binaries</label>
			<input type="checkbox" id="dodeploy">
		</fieldset>
		<!--Travis-Repo-ID: <input id="travisrepoid" value="14417672"></br>-->
		<fieldset>
			<legend>AppVeyor Settings</legend>
			<select id="avcompiler">
				<!-- Filled automatically on page load-->
			</select>
			<br>
			<label for="appveyorenv">Env:</label>
			<textarea id="appveyorenv" cols="100" rows="15">{}</textarea>
			<input id="buildbtnAV" type="button" value="Build on AppVeyor" onclick="buildappveyor()">
		</fieldset>
		<fieldset>
			<legend>
				<a href="https://docs.travis-ci.com/user/triggering-builds/">Travis settings</a>
			</legend>
			<input id="buildbtnTravis" type="button" value="Build on Travis" onclick="buildtravis()">
			<br>
			<label for="travisenv">Env:</label>
			<textarea id="travisenv" cols="100" rows="15">{}</textarea>
		</fieldset>
	</form>
	<div id="request">(Request data appears here)</div>
	<div id="result">(Request results appear here)</div>
</body>

</html>